import axios, { type InternalAxiosRequestConfig, type AxiosResponse } from "axios";
import config from "@/utils/config/index";
import { message } from 'antd';

const [messageApi] = message.useMessage();

// 创建 axios 实例
const service = axios.create({
  baseURL: config.baseUrl + config.baseApi,
  timeout: 6000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});


// 请求拦截器
service.interceptors.request.use(
  (cfg: InternalAxiosRequestConfig) => {

    if (localStorage.getItem("accessToken")) {
      cfg.headers.token = localStorage.getItem("accessToken");
    }

    return cfg;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {

    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof ArrayBuffer) {
      return response;
    }

    return response.data;
  },
  (error: any) => {

    if (error.response && error.response.data) {
      const { msg } = error.response.data;

      messageApi.error(msg || "系统出错");
    } else if (error) {
      messageApi.error(error.message || "系统出错");
    }
  }
);

// 导出 axios 实例
export default service;
